package com.coreJava.test02;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 作者: LCG
 * 日期: 2019/9/3 11:23
 * 描述:
 */
@RestController
public class NyTaskController {

    /**
     * 任务的合并
     */
    @RequestMapping("test0401")
    public void test0401(){

        CompletableFuture.supplyAsync(()->Test8.test00("AA",10))
                .thenCombine(CompletableFuture.supplyAsync(()->Test8.test00("BB",5)),
                        (x,y)->{
                            return x+y;
                        }
                ).thenAccept((result)->{
            System.out.println(result);
        });

    }

    /**
     * 最快完成任务
     */
    @RequestMapping("test0402")
    public void test0402(){

        List<CompletableFuture> list=new ArrayList<>();
        list.add( CompletableFuture.supplyAsync(()->Test8.test00("AA",5)));
        list.add( CompletableFuture.supplyAsync(()->Test8.test00("BB",4)));
        list.add( CompletableFuture.supplyAsync(()->Test8.test00("CC",1)));

        CompletableFuture<Object> objectCompletableFuture = CompletableFuture.anyOf(list.toArray(new CompletableFuture[list.size()]));

        //objectCompletableFuture.get();//同步获取结果
        //objectCompletableFuture.get(5,TimeUnit.SECONDS);//某个时间段内返回结果 获取不到直接返回 防止线程一直阻塞
        //objectCompletableFuture.getNow("55555");//立马获取结果，获取不到的话直接返回括弧中给的参数

        objectCompletableFuture.thenAccept((s)->{
            System.out.println("------>"+s);
        });


    }


    @RequestMapping("test0403")
    public void test0403(){

        List<CompletableFuture> list=new ArrayList<>();
        list.add( CompletableFuture.supplyAsync(()->Test8.test00("AA",5)));
        list.add( CompletableFuture.supplyAsync(()->Test8.test00("BB",4)));
        list.add( CompletableFuture.supplyAsync(()->Test8.test00("CC",1)));

        //执行所有的任务
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(list.toArray(new CompletableFuture[list.size()]));

        //编排任务的结果
        CompletableFuture<List<Object>> listCompletableFuture = voidCompletableFuture.thenApply((yy) -> {
            return list.stream().map(CompletableFuture::join).collect(Collectors.toList());
        });

        //收集错误
        CompletableFuture<List<Object>> exceptionally = listCompletableFuture.exceptionally((ex) -> {
            return Collections.singletonList(ex.getMessage());
        });

        listCompletableFuture.thenAccept((result)->{
            System.out.println(result);
        });

        exceptionally.thenAccept((error)->{
            System.out.println(error);
        });

    }

}
